package com.spark.lola.controller;

import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.support.api.entity.EnterpriseTokenUser;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.GeneratorUtil;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.core.param.MessageParam;
import com.spark.lola.support.core.param.UpdatePaswordRequest;
import com.spark.lola.support.wms.constant.RedisPrefix;
import com.spark.lola.support.wms.constant.SmsCodeConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Zhi-peng wang
 * @date: 2020/06/03 14:20
 **/
@Api(value = "/api/huarong/emp", tags = "用户接口")
@RequestMapping("/api/huarong/emp")
@RestController
public class EmpInfoController {
    private static final Logger logger = LoggerFactory.getLogger(EmpInfoController.class);

    @Autowired
    private RedisTemplate<String,String> systemRedis;
    @Autowired
    protected PortalServiceOpenApi portalServiceOpenApi;

    @ApiOperation(value = "获取用户信息")
    @RequestMapping(value = "/findUserInfo", method = RequestMethod.POST)
    public ResponseBean findUserInfo(@SessionAttribute EnterpriseTokenUser<?> tokenUser) {
        return ResponseBean.success(tokenUser);
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/update-password", method = RequestMethod.POST)
    public ResponseBean updatePassword(@RequestBody UpdatePaswordRequest request,@SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        if(StringUtils.isEmpty(request.getCode())){
            return ResponseBean.error("请输入短信验证码!");
        }
        if(!checkCode(tokenUser.getShiroUser(),request.getCode())) {
            return ResponseBean.error("验证码不正确!");
        }
        if(!request.getNewPassword().equals(request.getConfirmPassword())){
            return ResponseBean.error("新密码与确认密码不一致!");
        }
        return portalServiceOpenApi.updatePassword(request,tokenUser.getShiroUser().getId());
    }

    /**
     * 获取验证码
     */
    @ApiOperation(value = "获取验证码")
    @RequestMapping(value = "/code",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean code(@SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        String randomCode = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
        logger.info("===验证码【{}】", randomCode);
        Map<String, String> map = new HashMap<>();
        map.put("code", randomCode);
        MessageParam param = new MessageParam(SmsCodeConstant.VERIFICATION_CODE, "+86" + tokenUser.getShiroUser().getPhone(), map, null);
        ResponseBean responseBean = portalServiceOpenApi.sendMessage(param);
        if (responseBean.getCode() != 200) {
            throw new Exception(responseBean.getMessage());
        }
        systemRedis.opsForValue().set(RedisPrefix.CHECK_CODE + tokenUser.getShiroUser().getLoginNo(), randomCode, 10L, TimeUnit.MINUTES);
        logger.info("====手机【{}】获取证码【{}】===END===", tokenUser.getShiroUser().getPhone(), randomCode);
        return ResponseBean.success();
    }

    private Boolean checkCode(ShiroUser shiroUser, String code) throws Exception {
        String key = RedisPrefix.CHECK_CODE + shiroUser.getLoginNo();
        if (!systemRedis.hasKey(key)) {
            throw new Exception("请获取验证码!");
        }
        String checkCode = systemRedis.opsForValue().get(key);
        Boolean status = code.equals(checkCode);
        if (status) {
            systemRedis.delete(key);
        }
        return status;
    }
}
